package com.wlf.server.web.filter;


import cn.hutool.core.text.AntPathMatcher;
import com.wlf.server.common.config.XssConfig;
import com.wlf.server.common.xss.XssRequestWrapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author YSJ
 */
@Slf4j
@Service
public class XssFilter extends OncePerRequestFilter implements Ordered {

    @Resource
    private XssConfig xssConfig;

    /**
     * Xss过滤器 排序
     */
    @Override
    public int getOrder() {
        return FilterSort.XssFilter.getSort();
    }

    /**
     * 返回true则不经过此过滤器
     */
    @Override
    protected boolean shouldNotFilter(@NonNull HttpServletRequest request) throws ServletException {
        String servletPath = request.getServletPath();
        log.debug("servletPath={}", servletPath);
        // 如果为禁用xss,则不经过此过滤器。
        if (!xssConfig.getEnabled()) {
            return true;
        }
        // 排除过滤器
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String excludePath : xssConfig.getExcludes()) {
            if (pathMatcher.match(excludePath, servletPath)) {
                return true;
            }
        }
        return super.shouldNotFilter(request);
    }

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 核心就是这里
        filterChain.doFilter(new XssRequestWrapper(request), response);
    }
}